import winston from 'winston';
import * as path from 'path';
import * as fs from 'fs';

// 确保日志目录存在
const logDir = path.join(process.cwd(), 'logs');
if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true });
}

// 定义日志格式
const logFormat = winston.format.combine(
    winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.errors({ stack: true }),
    winston.format.splat(),
    winston.format.json()
);

// 定义控制台输出格式
const consoleFormat = winston.format.combine(
    winston.format.colorize(),
    winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss'
    }),
    winston.format.printf(
        info => `${info.timestamp} ${info.level}: ${info.message}`
    )
);

// 创建 logger 实例
const logger = winston.createLogger({
    level: process.env.LOG_LEVEL || 'info',
    format: logFormat,
    defaultMeta: { service: 'dev-assistant' },
    transports: [
        // 写入所有日志到 combined.log
        new winston.transports.File({
            filename: path.join(logDir, 'combined.log'),
            maxsize: 10 * 1024 * 1024, // 10MB
            maxFiles: 5,
            tailable: true
        }),
        // 写入错误日志到 error.log
        new winston.transports.File({
            filename: path.join(logDir, 'error.log'),
            level: 'error',
            maxsize: 10 * 1024 * 1024, // 10MB
            maxFiles: 5,
            tailable: true
        }),
        // 控制台输出
        new winston.transports.Console({
            format: consoleFormat
        })
    ]
});

// 在开发环境下，记录更详细的日志
if (process.env.NODE_ENV !== 'production') {
    logger.level = 'debug';
}

// 创建一个简单的性能监控函数
const startTimer = () => {
    const start = process.hrtime();
    return () => {
        const [seconds, nanoseconds] = process.hrtime(start);
        return seconds * 1000 + nanoseconds / 1000000; // 返回毫秒
    };
};

// 扩展 logger 接口
interface ExtendedLogger extends winston.Logger {
    startTimer: () => () => number;
    measureTime: (label: string, fn: () => Promise<any>) => Promise<any>;
}

// 添加性能监控方法
const extendedLogger = logger as ExtendedLogger;
extendedLogger.startTimer = startTimer;

// 添加测量执行时间的辅助方法
extendedLogger.measureTime = async (label: string, fn: () => Promise<any>) => {
    const timer = startTimer();
    try {
        const result = await fn();
        const duration = timer();
        logger.info(`${label} completed in ${duration.toFixed(2)}ms`);
        return result;
    } catch (error) {
        const duration = timer();
        logger.error(`${label} failed after ${duration.toFixed(2)}ms`, { error });
        throw error;
    }
};

// 导出扩展后的 logger
export default extendedLogger;

// 导出日志级别类型
export type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'silly';

// 使用示例：
/*
import logger from './utils/logger';

// 基本日志记录
logger.info('Application started');
logger.error('An error occurred', { error: new Error('Something went wrong') });
logger.debug('Debug information', { details: { foo: 'bar' } });

// 性能监控
const timer = logger.startTimer();
// ... 执行一些操作
const duration = timer();
logger.info(`Operation completed in ${duration}ms`);

// 测量异步操作时间
await logger.measureTime('Database query', async () => {
  // ... 执行数据库查询
  return results;
});
*/